<template>
  <base-container :footer="isActivated" is-template :show-title="false" :footerH="true">
    <base-container>
      <QueryFieldsHJBW
        ref="QueryFieldsRef"
        v-model:type="type"
        v-model:bw="BwFormFields"
        v-model:cibao="CiBaoFormFields"
        v-model:get-result="getResult"
        v-model:HjbwFormFields="HJBWFormFields"
        :package-list="packageList"
        :submitting="loading"
        :bw-submitting="bwSearching"
        :LandingPageList="LandingPageList"
        :combo-price-list="comboPriceList"
        :combo-price-loading="comboPriceLoading"
        :code="code"
        @sd-submit="sdLoadKeywordList"
        @cibao-reset="handleCiBaoReset"
        @cibao-package-change="handlePackageChange"
        @hjbw-submit="hjbwLoadKeywordList"
        @bw-submit="handleBwSearcher"
        @bw-reset="handleBwReset"
        @bw-jiekshuj="handleBwResetiusid"
      />

      <div>
        <Divider />
        <table-toolbar>
          <template #bar-left>
            <div>
              <span class="font-bold ft-16">推广关键词</span>
              <ForbiddenText :category="type" />
              <span class="hot-container" v-if="currentPackage.id === 26 || currentPackage.id === 31">
                <span
                  >当前套餐总热度：PC端：{{ currentPackage.pcHeatLimit }} / 移动端：{{ currentPackage.wapHeatLimit }}
                </span>
                <span
                  >剩余可选热度：PC端：{{ currentPackage.pcHeatLimit - pcHeat }} / 移动端：{{
                    currentPackage.wapHeatLimit - wapHeat
                  }}
                </span>
              </span>
              <span class="hot-container" v-else>
                <span>当前套餐总热度：{{ maxHeat }}</span>
                <span>剩余可选热度：{{ maxHeat - totalHeatRate }}</span>
              </span>
            </div>
          </template>
        </table-toolbar>
        <a-row :gutter="16">
          <a-col :span="12">
            <KeywordTable
              :loading="keywordLoading"
              :max-length="currentPackage?.wordsNumTotal ?? 0"
              :currentPackage="currentPackage"
              :type="type"
              :comboId="CiBaoFormFields.packageId"
              v-model:keyword-table-data="rawKeywordTableData"
              v-model:selected-table-data="selectedTableData"
            />
          </a-col>
          <a-col :span="12">
            <SelectedTable
              :type="type"
              v-model:raw-keyword-table-data="rawKeywordTableData"
              v-model:selected-table-data="selectedTableData"
            />
          </a-col>
        </a-row>
      </div>
    </base-container>

    <div v-show="getResult && (BW || BWYXB)">
      <BaseContainer class="mt-5" :show-title="false">
        <HotWordDetail :version-type="versionType" :phoenix-checker="phoenixChecker" :data="bwPriceInfo.wordAskWords" />
      </BaseContainer>
      <BaseContainer class="mt-5" :show-title="false">
        <BwBaidu
          :coordinates-hook="coordinatesHook"
          :price-utils="proPriceUtils"
          :mobile-sold="mobileSold"
          :pc-sold="pcSold"
          :pc-disable="pcDisable"
          :mobile-disable="mobileDisable"
          :bwPriceInfo="bwPriceInfo"
          v-model:creative-select="creativeSelect"
          v-model:qihu360-select="qihu360Select"
          v-model:type="type"
          @cibao-reset="handleCiBaoReset"
          @bw-reset="handleBwReset"
        />
        <BwPremium :premiums="premiums" />
      </BaseContainer>
    </div>

    <div>
      <BwSDFooter
        :btn-text="btnText"
        :selectedTableData="selectedTableData"
        :total-price="proTotalPrice"
        :currentPackage="currentPackage"
        @submit="handleSubmit"
        >套餐价格：{{ discount === 0 ? sdPrice.premiumPrice : sdPrice.premiumDiscountPrice }}
      </BwSDFooter>
    </div>

    <BwSDInfo :currentPackage="currentPackage" :discount="discount">
      优惠选择：<a-radio-group class="discount-radio" v-model:value="discount" :options="discountOptions" />
    </BwSDInfo>
  </base-container>
</template>

<script lang="ts" setup>
import { computed, defineOptions, onActivated, onDeactivated, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { intersectionWith } from 'lodash-es'
import TableToolbar from '@/components/table-toolbar/index.vue'
import getSdKeywordList, { type sdPriceAskParams } from '@/services/price-sheet/getSdKeywordList'
import getPackageList, { type PackageData } from '@/services/price-sheet/getPackageList'
import createPriceSheet from '@/services/price-sheet/createPriceSheet'
import { useMainStore } from '@/store/useMainStore'
import { usePriceSheetStore } from '@/store/usePriceSheetStore'
import type { VersionItem } from '@/views/price-sheet/interface'
import { message, Modal } from 'ant-design-vue'
import KeywordTable from '@/views/price-sheet/components/KeywordTable.vue'
import SelectedTable from '@/views/price-sheet/components/SelectedTable.vue'
import BaseContainer from '@/components/base-container/index.vue'
import HotWordDetail from '@/views/price-sheet/components/HotWordDetail.vue'
import ForbiddenText from '@/views/price-sheet/components/ForbiddenText.vue'
import BwBaidu from '@/views/price-sheet/components/BwBaidu.vue'
import QueryFields from '@/views/price-sheet/components/QueryFields.vue'
import type { BwPriceAskParams } from '@/services/price-sheet/getBwPriceAskWords'
import getBwPriceAskWords from '@/services/price-sheet/getBwPriceAskWords'
import { reactiveComputed } from '@vueuse/core'
import getComboPriceList from '@/services/price-sheet/getComboPriceList'
import Divider from '@/components/divider/index.vue'
import { useCategory } from '@/hooks/useCategotry'
import getPhoenixRegionCheckResult from '@/services/price-sheet/getPhoenixRegionCheckResult'
import type { PhoenixRegionCheckResult } from '@/services/price-sheet/getPhoenixRegionCheckResult'
import { TypeEnum, VersionTypeEnum, LandingPageEnum, IsFromHjzwEnum } from '@/core/enums/type'
import { ProductEnum } from '@/core/enums/platform'
import type { PriceKeyword } from '@/core/interfaces/keyword'
import { ApproveStatusEnum } from '@/core/enums/status'
import { DataIndex } from '@/core/enums/name'
import type { Coordinates } from '@/views/price-sheet/hooks/usePriceCoordinates'
import { usePriceCoordinates } from '@/views/price-sheet/hooks/usePriceCoordinates'
import { usePriceTable } from '@/views/price-sheet/hooks/usePriceTable'
import { useTotalPrice } from '@/views/price-sheet/hooks/useTotalPrice'
import { usePriceSold } from '@/views/price-sheet/hooks/usePriceSold'
import BwPremium from '@/views/price-sheet/components/BwPremium.vue'
import { useReloadModal } from '@/hooks/useReloadModal'
import { usePriceDisable } from '@/views/price-sheet/hooks/usePriceDisable'
import QueryFieldsHJBW from '@/views/price-sheet/components/QueryFieldsHJBW.vue'
import BwSDInfo from '@/views/price-sheet/components/BwSDInfo.vue'
import BwSDFooter from '@/views/price-sheet/components/BwSDFooter.vue'
import { toLabelValue } from '@/utils'
import { LandingPageMap } from '@/core/mapper/type'
import getKeywordListHjbw from '@/services/price-sheet/getKeywordListHjbw'
import type { HjbwPriceAskParams } from '@/services/price-sheet/getKeywordListHjbw'
import { byteLength } from '@/utils'
import { ComboPriceNameEnum } from '@/core/enums/name'
import { useRoute } from 'vue-router'
import { TypeCode } from '@/views/price-sheet/price-checking-by-category/type'

const route = useRoute()
const phoenixChecker = ref<Record<string, PhoenixRegionCheckResult>>({})

const code = computed(() => {
  return route.name
})

const yongjingeu = ref(false)

const dabiaogei = ref(false)
const dabiaogeis = ref(false)

const LandingPageList = computed(() => {
  return hjbwSelectedTableData.value?.length < 5
    ? toLabelValue(LandingPageMap).filter((item) => item.value !== 2)
    : toLabelValue(LandingPageMap)
})

defineOptions({
  name: 'PricePackage'
})

useReloadModal()
const router = useRouter()
const mainStore = useMainStore()
const priceSheetStore = usePriceSheetStore()

const loading = computed(() => {
  return keywordLoading.value || hjbwKeywordLoading.value
})

const [packageList, fetchPackageList] = getPackageList()
// const [rawKeywordTableData, fetchKeywordList, keywordLoading] = getKeywordList()
const [rawKeywordTableData, fetchKeywordListSD, keywordLoading] = getSdKeywordList()
const [rawKeywordTableDataHjbw, getKeywordListHjbwFn, hjbwKeywordLoading] = getKeywordListHjbw()
const [, fetchPriceSheet] = createPriceSheet()
const [bwPriceInfo, fetchBwPriceAskWord] = getBwPriceAskWords()
const [comboPriceList, fetchComboPriceList, comboPriceLoading] = getComboPriceList()
const [phoenixCheckerRes, fetchPhoenixRegionChecker] = getPhoenixRegionCheckResult()

// 点击特惠版传过来的id
const handleBwResetiusid = async (data) => {
  if (data.productId === 7) {
    await fetchPackageList({
      productId: 7
    })
    fetchComboPriceList({
      comboId: 4
    })
  } else {
    await fetchPackageList({
      productId: data.productId
    })
  }

  if (data.productId === 2) {
    fetchComboPriceList({
      comboId: 3
    })
  }

  if (data.productId === 6) {
    fetchComboPriceList({
      comboId: 3
    })
  }
}

const versionList = ref<VersionItem[]>([
  {
    title: '标准版',
    desc: '店铺显示商户电话，商户可根据需求自定义电话号码',
    active: true,
    id: VersionTypeEnum.Normal
  },
  {
    title: '普惠版',
    desc: '店铺不显示商户电话，平台400电话转接商户电话',
    active: false,
    id: VersionTypeEnum.Cheap
  },
  {
    title: '高级版',
    desc: '店铺显示商户电话，商户自定义店铺域名',
    active: false,
    id: VersionTypeEnum.Pro
  }
])

const defaultBwFormFields: () => BwPriceAskParams = () => ({
  biaowang: ProductEnum.BW,
  priceAskWords: [],
  serviceAreas: [],
  zzbwOrderNo: '',
  userAreas: [],
  assessmentPricesId: 0
})

const defaultSDFormFields: () => sdPriceAskParams = () => ({
  cibao: ProductEnum.BWSDYXB,
  packageId: undefined,
  comboPriceId: undefined,
  zzbwOrderNo: '',
  keyword: '',
  serviceAreas: []
})

const defaultHJBWFormFields: () => HjbwPriceAskParams = () => ({
  cibao: ProductEnum.HJBW,
  packageId: undefined,
  comboPriceId: undefined,
  comboPriceName: ComboPriceNameEnum.YEAR,
  keyword: undefined,
  onLinePeriod: '7*24',
  shopType: LandingPageEnum.SinglePage,
  comboPrice: undefined,
  hzTransferCode: IsFromHjzwEnum.Yes,
  hzNotes: undefined,
  zzbwOrderNo: ''
})
const marketPrice = ref<number>()

const bwSearching = ref(false)
const getResult = ref(false)
const isActivated = ref(false)
const creativeSelect = ref(false)
const qihu360Select = ref(false)
const QueryFieldsRef = ref<InstanceType<typeof QueryFields>>()
const selectedTableData = ref<PriceKeyword[]>([])
const keywordTableData = ref<PriceKeyword[]>([])
const hjbwSelectedTableData = ref<PriceKeyword[]>([])
const hjbwKeywordTableData = ref<PriceKeyword[]>([])
const BwFormFields = ref<BwPriceAskParams>(defaultBwFormFields())
const CiBaoFormFields = ref<any>(defaultSDFormFields())
const HJBWFormFields = ref<HjbwPriceAskParams>(defaultHJBWFormFields())
const type = ref<ProductEnum>(ProductEnum.CBTEH)
// 打印type的值
const discount = ref(0)
const discountOptions = ref([
  { label: '活动+原价', value: 0 },
  { label: '限时89折', value: 1 }
])
watch(
  () => code.value,
  (val) => {
    if (val === TypeCode.BW) {
      type.value = ProductEnum.BWYXB
    } else if (val === TypeCode.HJ) {
      type.value = ProductEnum.HJBW
    } else if (val === TypeCode.CB) {
      type.value = ProductEnum.CBYXB
    } else if (val === TypeCode.WB) {
      type.value = ProductEnum.WbBao
    } else if (val === TypeCode.DF) {
      type.value = ProductEnum.CBTEH
    } else if (val === TypeCode.SD) {
      type.value = ProductEnum.BWSDYXB
    }
  },
  {
    deep: true,
    immediate: true
  }
)
// const type = computed(() => {
//   return code.value === TypeCode.BW ? ProductEnum.BW : code.value === TypeCode.HJ ? ProductEnum.HJBW : ProductEnum.CiBao
// })
const { BW, CiBao, BWYXB, CBYXB } = useCategory(type)

const queryFields = reactiveComputed(() => {
  return BW.value || BWYXB.value ? BwFormFields.value : CiBao || CBYXB ? CiBaoFormFields.value : HJBWFormFields.value
})
const versionType = computed(() => {
  return versionList.value.find((v) => v.active)?.id ?? VersionTypeEnum.Normal
})
const assessmentPrices = computed(() => {
  return bwPriceInfo.assessmentPrices
})
const premiums = computed(() => {
  return bwPriceInfo.premiums || []
})
const morzjos = ref({
  id: 12,
  comboId: 5,
  type: 4,
  info: '年单',
  price: 1000
})
const comboPriceData = computed(() => {
  // 尝试找到匹配的 comboPriceId
  const found = comboPriceList.value.find((c) => c.id === CiBaoFormFields.value.comboPriceId)

  // 如果没有找到匹配的值，或者 CiBaoFormFields.value.comboPriceId 是空的，则返回默认值
  if (!found || !CiBaoFormFields.value.comboPriceId) {
    // 设置默认值，这里假设默认值是 comboPriceList 的第一个项目
    return comboPriceList.value.length > 0 ? comboPriceList.value[0] : morzjos.value
  }

  // 如果找到了匹配的值，则返回该值
  return found

  // return comboPriceList.value.find((c) => c.id === CiBaoFormFields.value.comboPriceId)
})

const coordinatesHook = usePriceCoordinates()
usePriceTable(coordinatesHook, assessmentPrices)

const { mobileDisable, pcDisable } = usePriceDisable(bwPriceInfo)
const { mobileSold, pcSold } = usePriceSold(bwPriceInfo, versionType, phoenixChecker, BwFormFields, type.value)
const { resetCoordinates, setBaiduCoordinates, set360Coordinates } = coordinatesHook

const proPriceUtils = usePriceTable(coordinatesHook, assessmentPrices, premiums)
const proTotalPrice = useTotalPrice(
  proPriceUtils.currentBaiduPrice,
  proPriceUtils.current360Price,
  proPriceUtils.creativePrice,
  creativeSelect,
  qihu360Select
)

function defaultCoordinates(): Coordinates {
  if (mobileSold.value && pcSold.value) {
    return []
  }

  if (pcDisable.value && mobileDisable.value) {
    return []
  }

  if (!pcSold.value && !mobileSold.value && !pcDisable.value && !mobileDisable.value) {
    return [0, DataIndex.Platform5x8]
  } else if (pcSold.value || pcDisable.value) {
    return [0, DataIndex.Mobile5x8]
  } else if (mobileSold.value || mobileDisable.value) {
    return [0, DataIndex.Pc5x8]
  } else {
    return []
  }
}

const btnText = computed(() => {
  if (bwPriceInfo.failtureCode) {
    return '提交审核'
  } else {
    return '提交审核'
  }
})
const currentPackage = computed<Partial<PackageData>>(() => {
  return packageList.value.find((p) => p.id === CiBaoFormFields.value.packageId) || {}
})

//
function resetVersionList() {
  versionList.value.forEach((v) => {
    v.active = false
  })
  versionList.value[0].active = true
}

async function handleBwSearcher() {
  getResult.value = false
  bwSearching.value = true
  bwDataReset()
  if (type.value !== ProductEnum.BWYXB && type.value !== ProductEnum.CBYXB) {
    const [phoenixErr] = await fetchPhoenixRegionChecker({
      keywords: BwFormFields.value.priceAskWords
    })
    if (!phoenixErr) {
      phoenixChecker.value = phoenixCheckerRes.value
    } else {
      bwSearching.value = false
      return message.error(phoenixErr?.message, 5)
    }
  } else {
    phoenixChecker.value = {}
  }

  const [bwErr] = await fetchBwPriceAskWord({ ...BwFormFields.value, productId: type.value })
  if (bwErr) {
    bwSearching.value = false
    return message.error(bwErr?.message, 5)
  }
  bwSearching.value = false
  getResult.value = true

  if (bwPriceInfo.failtureCode) {
    message.warning(bwPriceInfo.msg, 5)
  } else {
    BwFormFields.value.assessmentPricesId = bwPriceInfo.assessmentPricesId
    message.success('关键词已审核通过，确认套餐后可以确认订单~')
  }

  // 这里设置坐标锁定标王百度的格子
  const coordinates = defaultCoordinates()
  setBaiduCoordinates(coordinates)
  set360Coordinates(coordinates)
}

async function sdLoadKeywordList(data) {
  console.log(data.productId, '查询套餐', packageList.value)

  if (Object.keys(currentPackage.value).length === 0) {
    message.error('请先选择套餐')
    return
  }
  console.log(CiBaoFormFields.value.packageId, '套餐查询id')

  // Loop through packageList to find the corresponding productId

  const foundPackage = packageList.value.find((pkg) => pkg.id === data.productId)
  // console.log(foundPackage, '查询套餐???')

  if (!foundPackage) {
    message.error('未找到对应的套餐')
    return
  }

  if ('cibao' in queryFields) {
    if (!queryFields.keyword) {
      message.error('请输入关键词')
      return
    }

    localStorage.setItem('newproductId', foundPackage.productId)
    console.log(CiBaoFormFields.value, 'CiBaoFormFields')

    const [err, res] = await fetchKeywordListSD({
      keyword: queryFields.keyword,
      productId: foundPackage.productId, // Use the found productId
      comboId: CiBaoFormFields.value.packageId,
      serviceAreas: CiBaoFormFields.value.serviceAreas
    })
    if (res.data.code === 0) {
      yongjingeu.value = true
    } else {
      yongjingeu.value = false
    }

    if (!err) {
      intersectionSelectedWord()
    }
  }
}
async function hjbwLoadKeywordList() {
  if (!HJBWFormFields.value.keyword) return message.warning('请输入需要查询的关键词！')
  const len = byteLength(HJBWFormFields.value.keyword)
  if (len < 8) return message.warning('关键词小于8个字节')
  const [err] = await getKeywordListHjbwFn({
    keyword: HJBWFormFields.value.keyword,
    productId: type.value
  })
  if (!err) {
    HjbwIntersectionSelectedWord()
  }
}

function intersectionSelectedWord() {
  const result = intersectionWith(
    rawKeywordTableData.value,
    selectedTableData.value,
    (a, b) => a.frontKey === b.frontKey
  )

  result.forEach((item) => {
    item.selected = true
  })

  keywordTableData.value = rawKeywordTableData.value
}

function HjbwIntersectionSelectedWord() {
  const result = intersectionWith(
    rawKeywordTableDataHjbw.value,
    hjbwSelectedTableData.value,
    (a, b) => a.frontKey === b.frontKey
  )

  result.forEach((item) => {
    item.selected = true
  })

  hjbwKeywordTableData.value = rawKeywordTableDataHjbw.value
}

watch(
  () => hjbwSelectedTableData.value.length,
  (val) => {
    if (val < 5) {
      marketPrice.value = 3680 * val
      HJBWFormFields.value.comboPrice = 2800 * val
      HJBWFormFields.value.shopType = LandingPageEnum.SinglePage
    } else if (val === 5) {
      marketPrice.value = 16800
      HJBWFormFields.value.comboPrice = 12800
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val > 5 && val < 10) {
      marketPrice.value = Number(((16800 / 5) * val).toFixed(2))
      HJBWFormFields.value.comboPrice = Number(((12800 / 5) * val).toFixed(2))
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val === 10) {
      marketPrice.value = 29800
      HJBWFormFields.value.comboPrice = 23800
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val > 10) {
      marketPrice.value = Number(((29800 / 10) * val).toFixed(2))
      HJBWFormFields.value.comboPrice = Number(((23800 / 10) * val).toFixed(2))
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    }
  }
)

function handleCiBaoReset() {
  CiBaoFormFields.value.keyword = ''
  selectedTableData.value = []
  rawKeywordTableData.value = []
  keywordTableData.value = []
}
function handleServiceChange() {
  selectedTableData.value = []
  rawKeywordTableData.value = []
  keywordTableData.value = []
}

function handleBwReset() {
  getResult.value = false
  BwFormFields.value = defaultBwFormFields()
  QueryFieldsRef.value?.handleBwReset()
  bwDataReset()
}

function bwDataReset() {
  resetCoordinates()
  resetVersionList()
  creativeSelect.value = false
  qihu360Select.value = false
}

async function loadPackageList() {
  const [err] = await fetchPackageList({
    productId: type.value
  })

  if (!err) {
    CiBaoFormFields.value.packageId = packageList.value[0]?.value

    if (CiBaoFormFields.value.packageId) {
      await handlePackageChange(CiBaoFormFields.value.packageId)
    }
  }
}
const comboIdfn = ref(0)
// 切换套餐
const sdPrice = ref({
  premiumPrice: 0,
  premiumDiscountPrice: 0
})
async function handlePackageChange(comboId: number) {
  console.log(comboId, '切换套餐')
  comboIdfn.value = comboId
  CiBaoFormFields.value.comboPriceId = undefined
  const [err, res] = await fetchComboPriceList({
    comboId
  })
  if (!err) {
    sdPrice.value.premiumPrice = res.data.data[0].premiumPrice
    sdPrice.value.premiumDiscountPrice = res.data.data[0].premiumDiscountPrice
  }
}
const moveUp = ref(1)
const addWord = ref(0)
async function handleSubmit() {
  if (dabiaogei.value) {
    moveUp.value = 1
  }
  if (dabiaogeis.value) {
    addWord.value = 1
  }

  const params = {
    comboPriceName: comboPriceData.value?.info,
    comboPriceId: comboPriceData.value?.id ?? 0,
    comboPrice: comboPriceData.value?.premiumPrice ?? 0,
    comboName: currentPackage.value?.comboName!,
    zzbwOrderNo: CiBaoFormFields.value?.zzbwOrderNo!,
    comboId: currentPackage.value?.id!,
    proxyId: mainStore.userInfo!.proxy_id,
    proxyName: mainStore.userInfo!.proxy_name,
    priceAskWords: selectedTableData.value,
    sellerName: mainStore.userInfo!.full_name,
    sellerId: mainStore.userInfo!.id,
    productId: type.value,
    // route.name == 'price-package-wb'
    // Number(localStorage.getItem('newproductId'))  type.value
    areas: CiBaoFormFields.value.serviceAreas.join(','),
    type: TypeEnum.NEW,
    versionType: VersionTypeEnum.Normal,
    approveStatus: ApproveStatusEnum.PENDING,
    moveUp: moveUp.value,
    addWord: addWord.value,
    machineExamine: bwPriceInfo.machineExamine,
    isDiscount: discount.value,
    // 新增字段
    premiumPrice: comboPriceData.value?.premiumPrice ?? 0,
    premiumRatio: comboPriceData.value?.premiumRatio ?? 0,
    marketPrice: comboPriceData.value?.marketPrice ?? 0
  }

  Modal.confirm({
    title: '提示',
    content: '确定提交审核',
    async onOk() {
      const [err] = await fetchPriceSheet(params)
      if (!err) {
        priceSheetStore.setPurchaseData({
          selectedData: selectedTableData.value,
          CibaoPriceData: {
            comboName: currentPackage.value.comboName,
            comboPriceName: comboPriceData.value.info
          },
          approveStatus: ApproveStatusEnum.PENDING,
          type: type.value
        })

        handleBwReset()
        handleCiBaoReset()

        router.replace({
          name: 'price-purchase'
        })
      }
    }
  })
}

const totalHeatRate = computed(() => {
  return selectedTableData.value.reduce((sum, item) => sum + Number(item.heatRate || 0), 0)
})
const maxHeat = computed(() => {
  const { id, pcHeatLimit, wapHeatLimit } = currentPackage.value
  if (id === 24 || id === 29 || id === 27 || id === 32) {
    return pcHeatLimit
  }
  //移动端
  if (id === 25 || id === 30 || id === 28 || id === 33) {
    return wapHeatLimit
  }
  return 0
})

// 计算 PC 和 WAP 的当前热度
const pcHeat = computed(() => {
  return selectedTableData.value
    .filter((item) => item.clientType === 0)
    .reduce((sum, item) => sum + (item.heatRate || 0), 0)
})

const wapHeat = computed(() => {
  return selectedTableData.value
    .filter((item) => item.clientType === 1)
    .reduce((sum, item) => sum + (item.heatRate || 0), 0)
})

watch(
  () => CiBaoFormFields.value.serviceAreas,
  () => {
    handleServiceChange()
  },
  {
    immediate: true,
    deep: true
  }
)
onMounted(() => {
  loadPackageList()
})

onActivated(() => {
  isActivated.value = true
})

onDeactivated(() => {
  isActivated.value = false
})
</script>

<style scoped lang="scss">
.toolbar {
  width: 700px;

  &-keyword {
    max-width: 326px;
    min-width: 250px;
  }

  &-local {
    padding-top: 5px;
    padding-bottom: 5px;
  }
}

.search-icon {
  color: #a6a6a6;
}

.hot-container {
  margin-left: 20px;

  span {
    margin-right: 30px;
    font-size: 16px;
  }
}

::v-deep .discount-radio {
  font-weight: 600;
  height: 40px;
}
</style>
